var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var index = require('./routes/index');
var users = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname,'files')));

app.all('*', function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
  res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
  res.header("X-Powered-By", ' 3.2.1')
  if (req.method == "OPTIONS") res.send(200); /*让options请求快速返回*/
  else next();
});

// app.use('/', index);
// app.use('/users', users);

const formidable = require('formidable');
const fs = require('fs');
// const rootDir = 'tmp';
// let html = '';
//目录深度优先遍历
// function walk(path) {
//     var dirList = fs.readdirSync(path);
//     html += "<ul>" + path;
//     dirList.forEach(function (item) {
//         if (fs.statSync(path + '/' + item).isDirectory()) {
//             walk(path + '/' + item);
//         } else {
//             html += "<li><a href=" + path + '/' + item + ">" + item + "</a></li>";
//         }
//     });
//     html += "</ul>";
// };
// 事例
// app.use('/start', function (req, res) {
//     console.log("Request handler 'start' was called.");

//     var body = '<html>' +
//         '<head>' +
//         '<meta http-equiv="Content-Type" content="text/html;' +
//         'charset=UTF-8" />' +
//         '</head>' +
//         '<body>' +
//         '<form action="/uploads" enctype="multipart/form-data"' +
//         'method="post">' +
//         '<input type="file" name="upload" multiple="multiple"><br/>' +
//         '<input type="submit" value="Upload file" />' +
//         '<form>' +
//         '</body>' +
//         '</html>';

//     res.writeHead(200, { "Content-Type": "text/html" });
//     res.write(body);
//     res.end();
// });
// 下载
app.use('/uploads', function (req, res) {
    console.log("Request handler 'upload' was called.");
    var form = new formidable.IncomingForm();
    form.parse(req, function (error, fields, files) {
        console.log("parsing done");
        if (files&&files.image&&files.image.name) {
            let myname = 'img/' + Date.parse(new Date()) + files.image.name;

            fs.renameSync(files.image.path, "files/img/" + Date.parse(new Date()) + files.image.name);  // fs.renameSync(files.upload.path, "tmp/"+files.upload.name);
            res.json({ code: 200, path: myname });
        } else {
        res.json({ code: 201, mes: '图片格式不符合规则！' });
        }
        // res.writeHead(200, {"Content-Type": "text/html"});
        // res.write(`<head> <meta http-equiv="Content-Type" 
        //     content="text/html;charset=UTF-8" /> </head>`);
        // res.write("received file:<br/>");
        // walk(rootDir);
        // res.write(html);
        // html = '';
        // res.end();
    });
});
// 显示
app.use('/show', function (request, response) {
    console.log("Request handler 'show' was called.");
    const img = request.body.img ;
    fs.readFile(img, "binary", function (error, file) {
        if (error) {
            response.writeHead(500, { "Content-Type": "text/plain" });
            response.write(error + "\n");
            response.end();
        } else {
            response.writeHead(200, { "Content-Type": "image/png" });
            response.write(file, "binary");
            response.end();
        }
    });
});


// catch 404 and forward to error handler
app.use(function (req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handler
app.use(function (err, req, res, next) {
    // set locals, only providing error in development
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};

    // render the error page
    res.status(err.status || 500);
    res.render('error');
});

module.exports = app;
